gpt4 book ai didi

java - 在主 Activity 中调用 fragment 时出错

转载 作者:行者123 更新时间:2023-12-01 11:37:19 24 4
gpt4 key购买 nike

我尝试在 onCreate 内的主要 Activity 中调用 fragment (菜单 fragment )。但它抛出错误(问题已解决)其他问题-> 调用 fragment 时,在获取数据时布局为空白。我在frameLayout 中调用了它。

这是 main.xml 的 xml 文件

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF">
<!-- The main content view -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"/>
<!-- The navigation drawer -->
<ListView android:id="@+id/list_view"
android:layout_width="320dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@color/grey"
android:dividerHeight="0dp"
android:background="#000000"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/homeListView"
android:background="#FFFFFF"
android:divider="@color/grey"
android:dividerHeight="1dp">
</ListView>



</android.support.v4.widget.DrawerLayout>

Home.xml -> 菜单 fragment 布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Topic"
android:textSize="30dp"
android:textColor="#000000"
android:fontFamily="sans-serif"
android:id="@+id/topic"
android:background="#ffffff"
android:padding="10dp"
android:textStyle="bold"
android:visibility="gone"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/homeListView"
android:background="#FFFFFF"
android:divider="@color/grey"
android:dividerHeight="1dp">
</ListView>

</LinearLayout>

这是 Main.java,我试图在 onCreate 方法中替换为 fragment 。

public class Main extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;

private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mDrawerMenu;

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mTitle = mDrawerTitle = getTitle();
mDrawerMenu = getResources().getStringArray(R.array.menu);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_view);

// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.custom_menu_list, mDrawerMenu));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

//Call Fragment
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MenuFragment fragment = new MenuFragment();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.commit();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}


//Action bar on item click events
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action buttons
switch(item.getItemId()) {
case R.id.menu_icon:
// create intent to perform web search for this planet
Log.d("Hello","Menu clicked");
mDrawerLayout.openDrawer(mDrawerList);
return true;
default:
return super.onOptionsItemSelected(item);
}
}

/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
Log.d("Hello", String.valueOf(position));
//Get the option name and compare
String text = ((TextView) arg1.findViewById(android.R.id.text1)).getText().toString();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Bundle data = new Bundle();
data.putString("Topic",text);
if(position == 0){
Log.d("Click","Home Clicked");
MenuFragment fragment = new MenuFragment();
fragment.setArguments(data);
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.commit();

}
else if(position == 1){
Log.d("Click","News Clicked 2");
NewsFragment fragment = new NewsFragment();
fragment.setArguments(data);
fragmentTransaction.replace(R.id.content_frame, fragment, String.valueOf(position));
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
else if(position == 2){
Log.d("Click","Opinion Clicked");
OpinionFragment OpF = new OpinionFragment();
OpF.setArguments(data);
fragmentTransaction.replace(R.id.content_frame, OpF, String.valueOf(position));
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
else if(position == 3){
Log.d("Click","Features Clicked");
FeaturesFragment FeF = new FeaturesFragment();
FeF.setArguments(data);
fragmentTransaction.replace(R.id.content_frame, FeF, String.valueOf(position));
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
else if(position == 4){
Log.d("Click","Arts Clicked");
ArtsFragment ArtsF = new ArtsFragment();
ArtsF.setArguments(data);
fragmentTransaction.replace(R.id.content_frame, ArtsF, String.valueOf(position));
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
else if(position == 5){
Log.d("Click","Sports Clicked");
SportsFragment SportsF = new SportsFragment();
SportsF.setArguments(data);
fragmentTransaction.replace(R.id.content_frame, SportsF, String.valueOf(position));
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
else if(position == 6){
Log.d("Click","Opinion Clicked");
BlogsFragment BlogsF = new BlogsFragment();
BlogsF.setArguments(data);
fragmentTransaction.replace(R.id.content_frame, BlogsF, String.valueOf(position));
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}


mDrawerLayout.closeDrawer(mDrawerList);
}
}

}

这是 MenuFragment.java 类

public class MenuFragment extends Fragment {
private ProgressDialog pDialog;// Progress Dialog
ListView newsList;
String my_url;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> postList; //Declare Array
private static String url = "http://wangeltmg.com/GKN_ADMIN/GET_POSTS/";
GetNews.CustomAdapter CA;

// JSON Node names
private static final String TAG_ID = "id";
private static final String POST_ALLPOSTS = "posts";
private static final String POST_ID = "ID";
private static final String POST_TITLE = "post_title";
private static final String POST_CONTENT = "post_content";
private static final String POST_DATE = "post_date";
private static final String GUID = "guid";

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment

View view = inflater.inflate(R.layout.home, container, false);
newsList = (ListView) view.findViewById(R.id.homeListView);
TextView topic = (TextView) view.findViewById(R.id.topic);
postList = new ArrayList<HashMap<String, String>>();
//Get arguments
Bundle args = getArguments();
String mytopic = args.getString("Topic");
newsList.setOnItemClickListener(new newsListClick());
getActivity().getActionBar().setTitle("GannonKnightNews");
//Set topic
topic.setText(mytopic.toUpperCase());
//Execute getContacts
new GetNews().execute();

return view;
}

public class newsListClick implements ListView.OnItemClickListener{

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("News List","Clicked " + id);
String text = postList.get(position).get(GUID).toString();
String post_title = postList.get(position).get(POST_TITLE).toString();
String post_desc = postList.get(position).get(POST_CONTENT).toString();
Log.d("PostCOntent--->",post_desc);
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

Bundle data = new Bundle();
data.putString("url", text);
data.putString(POST_TITLE, post_title);
data.putString(POST_CONTENT, post_desc);
SinglePost singleFrag = new SinglePost();
singleFrag.setArguments(data);
fragmentTransaction.replace(R.id.content_frame, singleFrag);
fragmentTransaction.commit();
}
}

//Async Task
private class GetNews extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();

}

@Override
protected Void doInBackground(Void... arg0) {

// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();

// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Strings", "Checking Json");
Log.d("Response: ", "> " + jsonStr);

if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// contacts JSONArray
JSONArray posts = null;
// Getting JSON Array node
posts = jsonObj.getJSONArray(POST_ALLPOSTS);

// looping through All Contacts
for (int i = 0; i < posts.length(); i++) {

JSONObject c = posts.getJSONObject(i);
Log.d("Post->",posts.getJSONObject(i).toString());

String id = c.getString(POST_ID);

Log.d("Post->ID",id);
String post_title = c.getString(POST_TITLE);
String post_content = c.getString(POST_CONTENT);
String guid = c.getString(GUID);
Log.d("GUID->",guid);
String post_date = c.getString(POST_DATE);

//String gender = c.getString(TAG_GENDER);

// tmp hashmap for single post
HashMap<String, String> post = new HashMap<String, String>();

// adding each child node to HashMap key => value
post.put(POST_ID, id);
post.put(POST_TITLE, post_title);
post.put(POST_CONTENT, post_content);
post.put(GUID, guid);
post.put(POST_DATE, post_date);
post.put("ListCount",String.valueOf(i));

// adding contact to contact list
postList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}

return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();

// Updating parsed JSON data into ListView
/*
ListAdapter adapter = new SimpleAdapter(getActivity(), postList, R.layout.list_item,
new String[] { POST_TITLE,POST_CONTENT, GUID },
new int[] {R.id.email, R.id.mobile, R.id.guid });

newsList.setAdapter(adapter);
*/
CA = new CustomAdapter( getActivity(), R.layout.list_item, postList);
newsList.setAdapter(CA);
}


public class CustomAdapter extends ArrayAdapter<HashMap<String, String>>{

private final ArrayList<HashMap<String, String>> objects;

public CustomAdapter(Context context, int resource, ArrayList<HashMap<String, String>> objects) {
//something is wrong with super
super(context, resource, objects);
inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.objects = objects;
}

@Override
public int getItemViewType(int position) {

return position;
}

public View getView(int position, View convertView, ViewGroup Parent){
//convertView = new ImageView();
//System.out.println("getView " + position + " " + convertView + " type = " + type);
if(convertView == null){

convertView = inflater.inflate(R.layout.list_item,null);

}

android.widget.ImageView postImage = (android.widget.ImageView) convertView.findViewById(R.id.img);
int getListPos = newsList.getFirstVisiblePosition();
//i set the count starting 0 and saved in the hashmap array
//to compare the first result with the first position of listview
int count = Integer.parseInt(objects.get(position).get("ListCount"));
my_url = objects.get(position).get(GUID);
if(getListPos == count) {
//LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_header,null);
TextView HeaderText = (TextView) convertView.findViewById(R.id.headertext);
TextView HeaderContent = (TextView) convertView.findViewById(R.id.headercontent);
TextView HeaderDate = (TextView) convertView.findViewById(R.id.header_date);
HeaderText.setText(objects.get(position).get(POST_TITLE).toUpperCase());
HeaderDate.setText(objects.get(position).get(POST_DATE));
HeaderContent.setText(objects.get(position).get(POST_CONTENT));
if(objects.get(position).get(GUID).equals("NULL")) {
postImage.setImageResource(R.drawable.default_bg);
}else{
new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
}
}
else{
//CHoose list item
//LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item,null);
TextView thisview = (TextView) convertView.findViewById(R.id.email);
TextView postContent = (TextView) convertView.findViewById(R.id.mobile);
thisview.setText(objects.get(position).get(POST_TITLE).toUpperCase());
postContent.setText(objects.get(position).get(POST_CONTENT));
if(objects.get(position).get(GUID).equals("NULL")) {
postImage.setImageResource(R.drawable.default_bg);
}else{
new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
}
}

return convertView;
}


}//Custom Adapter

}//END getnews Async Task

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;

public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}

protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}

protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}//

}

最佳答案

你应该改变

 String text = ((TextView) arg1.findViewById(android.R.id.text1)).getText().toString();

 String text = ((TextView) arg1.findViewById(R.id.text1)).getText().toString();

您的Textview ID 是text1。并且您正在尝试使用 android.R.id.text1

这可能是导致您出现问题的原因之一。

关于java - 在主 Activity 中调用 fragment 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29838896/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com