完成收支记录界面的逻辑编写
代码如下:
package com.example.myapplication1;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import com.example.myapplication1.adapter.RecordPagerAdapter;
import com.example.myapplication1.frag_record.IncomeFragment;
import com.example.myapplication1.frag_record.BaseRecordFragment;
import com.example.myapplication1.frag_record.OutcomeFragment;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import java.util.ArrayList;
import java.util.List;
public class RecordActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager2 viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
tabLayout = findViewById(R.id.record_tabs);
viewPager = findViewById(R.id.record_vp);
initPager();
View button = findViewById(R.id.record_iv_back);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
private void initPager() {
List<Fragment> fragmentList = new ArrayList<>();
OutcomeFragment outFrag = new OutcomeFragment();
IncomeFragment inFrag = new IncomeFragment();
fragmentList.add(outFrag);
fragmentList.add(inFrag);
RecordPagerAdapter pagerAdapter = new RecordPagerAdapter(this, fragmentList);
viewPager.setAdapter(pagerAdapter);
new TabLayoutMediator(tabLayout, viewPager,
(tab, position) -> tab.setText(pagerAdapter.getPageTitle(position).toString())
).attach();
}
}
相关适配器文件recordpageradapter
代码如下:
package com.example.myapplication1.adapter;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import com.example.myapplication1.RecordActivity;
import java.util.List;
public class RecordPagerAdapter extends FragmentStateAdapter {
List<Fragment> fragmentList;
String[] titles = {"支出", "收入"};
public RecordPagerAdapter(@NonNull RecordActivity fragment, List<Fragment> fragmentList) {
super(fragment);
this.fragmentList = fragmentList;
}
@NonNull
@Override
public Fragment createFragment(int position) {
return fragmentList.get(position);
}
@Override
public int getItemCount() {
return fragmentList.size();
}
public String getPageTitle(int position) {
return titles[position];
}
}
接着在主界面的代码上面加上点击“记一笔”跳转到收支界面的点击事件代码
标签:fragmentList,安卓,笔记,example,record,记账,import,com,public From: https://www.cnblogs.com/czfznb/p/18027984