需要有关将Android功能与预制视图集成的帮助

时间:2014-02-09 06:05:40

标签: android listview android-fragments

我刚刚接触到android和java,我正在尝试构建一个示例android应用程序。 我从androhive中获取了应用程序视图,看起来像google + app 并使我的功能跟随在线的许多教程 但我无法整合它们。 这是我的代码 这是我的片段样本,用于使用侧栏切换活动

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MHEFragment extends Fragment {

    public MHEFragment(){}

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

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

        return rootView;
    }
}

继承我的功能os listview

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {
    public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
 private String jsonResult;
 private String url = "http://192.168.129.1/1.php";
 private ListView listView;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  listView = (ListView) findViewById(R.id.listView1);
  accessWebService();
 }

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

 // Async Task to access the web
 private class JsonReadTask extends AsyncTask<String, Void, String> {
  @Override
  protected String doInBackground(String... params) {
   HttpClient httpclient = new DefaultHttpClient();
   HttpPost httppost = new HttpPost(params[0]);
   try {
    HttpResponse response = httpclient.execute(httppost);
    jsonResult = inputStreamToString(
      response.getEntity().getContent()).toString();
   }

   catch (ClientProtocolException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
   return null;
  }

  private StringBuilder inputStreamToString(InputStream is) {
   String rLine = "";
   StringBuilder answer = new StringBuilder();
   BufferedReader rd = new BufferedReader(new InputStreamReader(is));

   try {
    while ((rLine = rd.readLine()) != null) {
     answer.append(rLine);
    }
   }

   catch (IOException e) {
    // e.printStackTrace();
    Toast.makeText(getApplicationContext(),
      "Error..." + e.toString(), Toast.LENGTH_LONG).show();
   }
   return answer;
  }

  @Override
  protected void onPostExecute(String result) {
   ListDrwaer();
  }
 }// end async task

 public void accessWebService() {
  JsonReadTask task = new JsonReadTask();
  // passes values for the urls string array
  task.execute(new String[] { url });
 }

 // build hash set for list view
 public void ListDrwaer() {
  List<Map<String, String>> storyList = new ArrayList<Map<String, String>>();

  try {
   JSONObject jsonResponse = new JSONObject(jsonResult);
   JSONArray jsonMainNode = jsonResponse.optJSONArray("story");

   for (int i = 0; i < jsonMainNode.length(); i++) {
    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
    String name = jsonChildNode.optString("story_name");
    String number = jsonChildNode.getString("story_id").toString();
    String outPut = number + "-" + name;


    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapter, View name, int position,
                long number) {
             Intent intnt = new Intent(getApplicationContext(), Tester.class);  
             String deta = adapter.getItemAtPosition(position).toString();
            String myStr = deta.replaceAll( "[^\\d]", "" );
             intnt.putExtra(EXTRA_MESSAGE,myStr);
             startActivity(intnt);

        }
     });
    storyList.add(createStory("stories", outPut));
   }
  } catch (JSONException e) {
   Toast.makeText(getApplicationContext(), "Error" + e.toString(),
     Toast.LENGTH_SHORT).show();
  }

  SimpleAdapter simpleAdapter = new SimpleAdapter(this, storyList,
    android.R.layout.simple_list_item_1,
    new String[] { "stories" }, new int[] { android.R.id.text1 });
  listView.setAdapter(simpleAdapter);



 }

 private HashMap<String, String> createStory(String name, String number) {
  HashMap<String, String> storyNameNo = new HashMap<String, String>();
  storyNameNo.put(name, number);
  return storyNameNo;
 }
}

如何将listview集成到上面的片段中?

1 个答案:

答案 0 :(得分:0)

如果你想在片段中使用ListView,那么你最好使用你的片段,它将继承ListFragment。
ListFragment中的onCreateView()将返回一个可以填充的ListView http://developer.android.com/reference/android/app/ListFragment.html
http://www.vogella.com/tutorials/AndroidListView/article.html#listfragments

对于Fragments,如果你想要一个单独的ListView和更多的片段,如果你通过它会有所帮助:
http://www.easyinfogeek.com/2013/07/full-example-of-using-fragment-in.html
..更多的布局和调用onCreateView()

此外,(不是问题的一部分,但是来自&amp; for your code)如果有帮助,我建议

在每个循环中使用a代替(;;)
(在您的情况下:对于json主节点中的每个json子节点)

http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

How does the Java 'for each' loop work?