我有两个问题:1)当我尝试在oncreate()期间直接将fragment2加载到mainactivity时它没有显示任何内容2)当我创建一个按钮转到fragment2并单击按钮时 要转到fragment2,它将转到fragment2,但在第二次单击或双击同一按钮后转到。我已经尝试过使用setfocusableintouchmode = true和false两个,但得到相同的结果,按钮在相同的2次点击之后工作。那么这个网络操作是什么?如何显示要在mainactivity中显示的fragment2网络操作的结果?按钮怎么样?继承我的代码:
我的Androidmanifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
继承我的主要活动:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class MainActivity extends AppCompatActivity {
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Fragment frag2 = new Fragment2();
FragmentTransaction transaction =getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fl, frag2);
transaction.addToBackStack(null);
transaction.commit();
Log.i("reaktion","commited");
b1=(Button)findViewById(R.id.f1);
b2=(Button)findViewById(R.id.f2);
b2.setFocusableInTouchMode(false);
//
// Fragment2 frag2= new Fragment2();
// FragmentManager manager = getSupportFragmentManager();
// FragmentTransaction transaction = manager.beginTransaction(); //// I tried this, but as I said, it does nothing on oncreate ()
// transaction.replace(R.id.fl,frag2);
// transaction.commit();
//
}
public void frag1(View view){
Fragment newFragment = new Fragment1();
FragmentTransaction transaction =getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fl, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
public void frag2(View view){
Fragment2 frag2= new Fragment2();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fl,frag2);
transaction.commit();
}
}
我的片段1:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class Fragment1 extends Fragment {
Button btn;
public Fragment1() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
container.removeAllViewsInLayout();
View v= inflater.inflate(R.layout.fragment_fragment1, container, false);
btn=(Button)v.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment2 frag2= new Fragment2();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fl,frag2);
transaction.commit();
}
});
// Inflate the layout for this fragment
return v;
}
}
我的片段2:
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment2 extends Fragment {
static String j="";
RecyclerView rv;
private GridLayoutManager gridLayoutManager;
private myadapter adapter;
ArrayList<String> company_namelist;
ArrayList<String> company_websitelist;
String JR;
public Fragment2() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
container.removeAllViewsInLayout();
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_fragment2, container, false);
company_namelist =new ArrayList<>();
company_websitelist=new ArrayList<>();
loaddata();
Log.i("loadhua","connection request made");
rv = (RecyclerView)view.findViewById(R.id.recycler_view);
LinearLayoutManager linearLayoutManager= new LinearLayoutManager(getActivity());
adapter = new myadapter(company_namelist,company_websitelist);
rv.setLayoutManager(linearLayoutManager);
rv.setFocusableInTouchMode(false);
Log.i("jojojo","recycler has setted the adapter");
rv.setAdapter(adapter);
return view;
}
public void loaddata(){
companyfromserver obj = new companyfromserver();
JSONObject a = new JSONObject();
try {
a.put("nothing","nothing" );
} catch (JSONException e) {
e.printStackTrace();
}
obj.execute(String.valueOf(a));
JR=obj.getJR();
Log.i("nacho",JR);
try{
JSONObject jsonObject = new JSONObject(JR);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsondata = jsonArray.getJSONObject(i);
String company_name= jsondata.getString("company_name");
String company_website=jsondata.getString("company_website");
company_namelist.add(company_name);
company_websitelist.add(company_website);
}
}catch (JSONException e){}
}
}
companyfromserver:
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
class companyfromserver extends AsyncTask<String, String, String> {
public static String j="";
@Override
protected String doInBackground(String... params) {
String JsonResponse = "";
String JsonDATA = params[0];
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL("example.com");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
// is output buffer writter
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
//set headers and method
Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
writer.write(JsonDATA);
// json data
writer.close();
InputStream inputStream = urlConnection.getInputStream();
//input stream
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine + "\n");
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
JsonResponse = buffer.toString();
j=j+JsonResponse;
Log.i("xyz",j);
//response data
Log.i("o/p:", JsonResponse);
//send to post execute
}
catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("wtf", "Error closing stream", e);
}
}
}
return j;
}
public String getJR(){
Log.i("klopp",j);
return j; }
}
mainactivity.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<RelativeLayout
android:id="@+id/rl"
android:layout_width="0dp"
android:layout_height="0dp"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
android:layout_marginStart="8dp"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginEnd="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="8dp"
tools:layout_constraintLeft_creator="1"
android:layout_marginBottom="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp">
<FrameLayout
android:id="@+id/fl"
android:layout_marginTop="60sp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<Button
android:id="@+id/f1"
android:layout_width="100sp"
android:layout_height="50sp"
android:text="f1"
android:onClick="frag1"/>
<Button
android:layout_toRightOf="@+id/f1"
android:id="@+id/f2"
android:layout_marginLeft="30sp"
android:layout_width="100sp"
android:layout_height="50sp"
android:text="f2"
/>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
Fragment1.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_gravity="center"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="fragment 1" />
<Button
android:id="@+id/btn"
android:text="go"
android:layout_margin="80sp"
android:layout_width="140sp"
android:layout_height="60sp" />
</FrameLayout>
fragment2.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:focusable="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"
android:scrollbars="vertical" />
</FrameLayout>
答案 0 :(得分:0)
在onPostExecute中绑定数据或使用回调。
obj.execute(String.valueOf(a));
/* Here you wont be getting data */
JR=obj.getJR();
Log.i("nacho",JR);