[英]Add new textview in fragment after click on button in another fragment
我有两个片段。 在我点击第一个按钮后,它会移动到带有一些 SharedPreferences 的第二个片段。 每次单击该按钮时,我都想在第二个片段中使用来自 SharedPreferences 的文本在另一个下添加新的文本视图。
这是我想添加文本视图的第二个片段的代码
public class HomeFragment extends Fragment{
public HomeFragment() {
// Required empty public constructor
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("MyData", Context.MODE_PRIVATE);
String Income =sharedPreferences.getString("Income","N/A");
LinearLayout m_ll = (LinearLayout) view.findViewById(R.id.home);
m_ll.addView(createNewTextView(Income));
return m_ll;
}
private TextView createNewTextView(String text) {
final LinearLayoutCompat.LayoutParams lparams = new LinearLayoutCompat.LayoutParams(LinearLayoutCompat.LayoutParams.WRAP_CONTENT, LinearLayoutCompat.LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(getActivity());
textView.setLayoutParams(lparams);
textView.setText("New text: " + text);
return textView;
}
}
它添加带有正确文本的文本视图,但是下次当我按下按钮时,它只会更改文本视图的文本(或在另一个文本视图上创建一个文本视图?)
XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/home"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.xxxx.HomeFragment">
<!-- TODO: Update blank fragment layout -->
</LinearLayout>
我设法让它与 TinyDB 一起工作,它可以将字符串数组列表存储为 SharedPreferences。
这就是我在带有按钮的片段中所拥有的
TinyDB tinydb=new TinyDB(getActivity().getApplicationContext());
incometemp = edttxt.getText().toString();
mylist= tinydb.getListString("income");
mylist.add(incometemp );
tinydb.putListString("income", mylist);
第二个片段
TinyDB tinydb;
ArrayList<String> mylist = new ArrayList<>();
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
tinydb = new TinyDB(getActivity().getApplicationContext());
mylist = tinydb.getListString("income");
LinearLayout m_ll = (LinearLayout) view.findViewById(R.id.home);
for (int i=0;i<mylist.size();i++) {
m_ll.addView(createNewTextView(mylist.get(i)));
}
return m_ll;
}
private TextView createNewTextView(String text) {
final LinearLayoutCompat.LayoutParams lparams = new LinearLayoutCompat.LayoutParams(LinearLayoutCompat.LayoutParams.WRAP_CONTENT, LinearLayoutCompat.LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(getActivity());
textView.setLayoutParams(lparams);
textView.setText("New text: " + text);
return textView;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.