我有两个片段。单击第一个按钮后,它会移动到带有一些SharedPreferences的第二个片段。每次我点击那个按钮,我想在另一个下面添加新的textview,并在第二个片段中添加来自SharedPreferences的文本。
以下是我要添加textviews的第二个片段的代码
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;
}
}
它使用正确的文本添加textview,但是下次按下按钮时它只是更改textview的文本(或在另一个上创建一个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>
答案 0 :(得分:0)
我设法使它与TinyDB一起使用,它可以将字符串arraylist存储为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;
}
}