在列表视图中接收一堆文本

时间:2015-04-27 20:09:17

标签: java android listview

我想要做的是每次点击“添加”按钮,都会通过列表视图将新单词添加到“测试”类中。到目前为止我所做的只会在textview中添加一个单词。但我想要的是,只要点击添加按钮,就会在列表视图中添加一个新单词。我怎么做?这是我的代码:

public class MainActivity extends Activity {

private EditText mainedit1;
private TextView maintext1;
private Button   mainadd1;
private Button   maindone1;
@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    maindone1=(Button) findViewById(R.id.maindone);
    mainedit1=(EditText)findViewById(R.id.mainedit1);
    maintext1=(TextView)findViewById(R.id.maintext1);
    mainadd1=(Button)findViewById(R.id.mainadd);

    mainadd1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String test1 = mainedit1.getText().toString();

            getSharedPreferences("my_prefs",      Context.MODE_PRIVATE).edit().putString("word", test1).commit();
            Toast.makeText(getApplicationContext(),"Word added",Toast.LENGTH_SHORT).show();
            mainedit1.setText(null);
        }
    });

 maindone1.setOnClickListener( new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         Intent intent = new Intent(MainActivity.this,test.class);
         startActivity(intent);


     }
 });
}
}

测试类:

public class test extends Activity {
TextView testtext;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fortest);
    testtext=(TextView)findViewById(R.id.testtext);


    getSharedPreferences("my_prefs", Context.MODE_PRIVATE).getString("word", null);
    String Word1 = getSharedPreferences("my_prefs",MODE_PRIVATE).getString("word",null).toString();
    testtext.setText(Word1);
}
}

如果您知道,请通过尝试代码告诉我如何操作。

2 个答案:

答案 0 :(得分:1)

每次单击按钮时,您似乎都会覆盖密钥:"word"下的内容。您应该获取当前值,使用新单词更新它,然后添加。

替换:

getSharedPreferences("my_prefs", Context.MODE_PRIVATE).edit().putString("word", test1).commit();

使用:

String currentString = etSharedPreferences("my_prefs", Context.MODE_PRIVATE).getString("word", "");
getSharedPreferences("my_prefs", Context.MODE_PRIVATE).edit().putString("word", currentString + ", "+test1).commit();

请将内容从第二个侦听器移到第一个侦听器并删除第二个侦听器。

答案 1 :(得分:0)

您应该使用片段来保存列表视图。让你的活动保持这个片段。这样您就不会尝试将所有数据从一个活动传递到下一个活动,您只需将其添加到显示它的同一活动中即可。

所以你最终会得到一个像以下一样的MainActivity:

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new WidgetFragment())
                .commit();
    }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
 }
}

片段类:

public class WidgetFragment extends Fragment {

private ArrayAdapter<String> widgetAdapter;

public WidgetFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Add this line in order for this fragment to handle menu events.
    setHasOptionsMenu(true);



}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.widgetfragment, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_refresh) {
        FetchWidgetData widgetTask = new FetchWidgetData();
        widgetTask.execute("50131");
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Create some dummy data for the ListView.  Here's a sample weekly forecast
    String[] data = {
            "Dummy Data",
            "Just an Example",
            "Delete at anytime",
            "Project 4",
            "Project 5",
            "Filler Data",
    };
    List<String> listData = new ArrayList<String>(Arrays.asList(data));

    // Now that we have some dummy forecast data, create an ArrayAdapter.
    // The ArrayAdapter will take data from a source (like our dummy forecast) and
    // use it to populate the ListView it's attached to.
    widgetAdapter =
            new ArrayAdapter<String>(
                    getActivity(), // The current context (this activity)
                    R.layout.list_item_widget, // The name of the layout ID.
                    R.id.list_item_widget_textview, // The ID of the textview to populate.
                    listData);

    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

    // Get a reference to the ListView, and attach this adapter to it.
    ListView listView = (ListView) rootView.findViewById(R.id.listview_widget);
    listView.setAdapter(widgetAdapter);

    //!!!You can add your button click listener here. And put the following line inside it to add data to your list adapter!!!
    widgetAdapter.add("whatever whatever whatever"); //appends to end of list
    widgetAdapter.clear(); //to reset/clear the whole thing.
    widgetAdapter.remove(widgetAdapter.getItem(index); //removes the desired object. Note - remove takes object not an index.

    return rootView;
}

}

编辑:键列表查看步骤。

1)创建对列表视图所在的根视图的引用

View rootView = inflater.inflate(R.layout.fragment_main, container, false);

2)创建一个适配器来保存数据。

widgetAdapter =
            new ArrayAdapter<String>(
                    getActivity(), // The current context (this activity)
                    R.layout.list_item_widget, // The name of the layout ID.
                    R.id.list_item_widget_textview, // The ID of the textview to populate.
                    new ArrayList<String>);

3)创建对listview本身的引用

ListView listView = (ListView) rootView.findViewById(R.id.listview_widget);

4)设置listview适配器

ListView.setAdapter(widgetAdapter);

5)将数据添加到适配器

widgetAdapter.add("Whatever");

编辑:添加到Main Activity类的示例静态方法,假设您已将列表适配器声明为静态类变量,

public static void addWordToList(String word){
   listAdapter.add(word); //LIST ADAPTER MUST BE STATIC OR THERE MAY BE NO INSTANCE OF IT
   }
}

然后你可以通过

从测试活动中调用它
MainActivity.addWordToList("Whatever word you want to add");