我在执行代码时发现了一些奇怪的东西。
我删除了很多代码以尝试检测错误。
我使用两个片段。
在第一个片段中,我使用volley +从数据库中读取。 通过单击片段加载新片段时,前一片段的onclik事件将继续对新片段起作用。
代码在RecyclerView中正确执行,从远程数据库读取数据并且未检测到错误。
第二个片段的代码:CommentariosArticulo我没有把因为它是空的,只有android Studio生成的默认模板
我还验证了如果删除所有代码 片段内部:ListadoArticulos.java 参考齐射并参考Recyclerview并调用第二个片段问题消失
Articulo.java
---------------
public class Articulo {
private Integer id;
private String titulo;
private String contenido;
private String fecha;
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
public String getTitulo() { return titulo; }
public void setTitulo(String titulo) { this.titulo = titulo; }
public String getContenido() { return contenido; }
public void setContenido(String contenido) { this.contenido = contenido; }
public String getFecha() { return fecha; }
public void setFecha(String fecha) { this.fecha = fecha; }
}
ArticulosAdapter.java
---------------------
package com.example.suso.audioblogsuso_pru003.datos;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.suso.audioblogsuso_pru003.R;
import java.util.List;
public class ArticulosAdapter extends
RecyclerView.Adapter<ArticulosAdapter.ArticulosHolder>
implements View.OnClickListener{
private List<Articulo> listaArticulos;
private View.OnClickListener onClickListener;
public ArticulosAdapter(List<Articulo> listaArticulos) {
this.listaArticulos = listaArticulos;
}
@Override
public ArticulosHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View vista= LayoutInflater.from(parent.getContext()).
inflate(R.layout.articulos_item,parent,false);
RecyclerView.LayoutParams layoutParams=new RecyclerView.
LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
vista.setLayoutParams(layoutParams);
vista.setOnClickListener(this); // para que capte el evento click
return new ArticulosHolder(vista);
}
@Override
public void onBindViewHolder(ArticulosHolder holder, int position) {
holder.txtId.setText(listaArticulos.get(position).getId().toString());
holder.txtTitulo.setText(listaArticulos.get(position).getTitulo().toString());
holder.txtFecha.setText(listaArticulos.get(position).getFecha().toString());
}
@Override
public int getItemCount() {
return listaArticulos.size();
}
public void setOnClickListener(View.OnClickListener onClickListener){
this.onClickListener = onClickListener;
}
@Override
public void onClick(View v) {
if(onClickListener != null){
onClickListener.onClick(v);
}
}
public class ArticulosHolder extends RecyclerView.ViewHolder{
TextView txtId, txtTitulo, txtFecha;
public ArticulosHolder(View itemView) {
super(itemView);
txtId = (TextView) itemView.findViewById(R.id.idArticulo);
txtTitulo = (TextView) itemView.findViewById(R.id.tituloArticulo);
txtFecha =(TextView) itemView.findViewById(R.id.fechaArticulo);
}
}
}
mainActivity.java
-----------------
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener ,
ComentariosArticulo.OnFragmentInteractionListener,
ListadoArticulos.OnFragmentInteractionListener
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@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;
}
@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);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment miFragment = null;
boolean fragmentSeleccionado = false;
if (id == R.id.listadoArticulos) {
miFragment = new ListadoArticulos();
fragmentSeleccionado=true;
}
if(fragmentSeleccionado){
getSupportFragmentManager().beginTransaction().replace(R.id.content_main,miFragment).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onFragmentInteraction(Uri uri) {
}
Listado Articulos.java
----------------------
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link ListadoArticulos.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link ListadoArticulos#newInstance} factory method to
* create an instance of this fragment.
*/
public class ListadoArticulos extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
MiAplicacion miAplicacion;
RecyclerView recyclerArticulos;
ArrayList<Articulo> listaArticulos;
RequestQueue request;
JsonObjectRequest jsonObjectRequest;
TextView tvLoadingListadoArticulos;
public ListadoArticulos() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ListadoArticulos.
*/
// TODO: Rename and change types and number of parameters
public static ListadoArticulos newInstance(String param1, String param2) {
ListadoArticulos fragment = new ListadoArticulos();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_listado_articulos, container, false);
miAplicacion = (MiAplicacion) getContext().getApplicationContext();
tvLoadingListadoArticulos = (TextView) view.findViewById(R.id.tvLoadingListadoArticulos);
listaArticulos=new ArrayList<>();
recyclerArticulos= (RecyclerView) view.findViewById(R.id.IdReciclerViewListadoArticulos);
//El LayoutManager se encarga del layout de todas las vistas dentro del RecyclerView
recyclerArticulos.setLayoutManager(new LinearLayoutManager(this.getContext()));
//el tamaño del recyclerView no depende del adaptador
recyclerArticulos.setHasFixedSize(true);
request = Volley.newRequestQueue(getContext());
request.getCache().clear();
cargarWebServiceWeb();
return view;
}
private void cargarWebServiceWeb() {
String scriptPhp ="listado-articulos.php";
String url= miAplicacion.getUrlHostScriptPhp()+scriptPhp;
jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
url,
null,
createMyReqSuccessListenerArticulos(),
createMyReqErrorListenerArticulos());
request.add(jsonObjectRequest);
}
private Response.Listener<JSONObject> createMyReqSuccessListenerArticulos() {
return new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if(response.isNull("articulos")){
Toast.makeText(getContext(), "No se encontró ningun articulo " , Toast.LENGTH_LONG).show();
tvLoadingListadoArticulos.setHeight(0);
return;
}
Articulo articulo=null;
JSONArray json=response.optJSONArray("articulos");
try {
for (int i=0;i<json.length();i++){
articulo=new Articulo();
JSONObject jsonObject=null;
jsonObject=json.getJSONObject(i);
articulo.setId((Integer)jsonObject.optInt("ID"));
articulo.setTitulo(jsonObject.optString("post_title"));
articulo.setContenido(jsonObject.optString("post_content"));
articulo.setFecha("fecha");
listaArticulos.add(articulo);
}
ArticulosAdapter adapter=new ArticulosAdapter(listaArticulos);
adapter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(),"estoy creando un nuevo fragment", Toast.LENGTH_LONG).show();
// Crea el nuevo fragmento y la transacción.
Fragment miFragment = new ComentariosArticulo();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
//el id:R.id.BuscarArticulosCategoria pertenece al
//contenedor del fragment_buscar_articulos_categoria.xml (fragment actual)
transaction.replace(R.id.contenListadoArticulos, miFragment);
transaction.addToBackStack(null);
// Commit a la transacción
transaction.commit();
}
});
tvLoadingListadoArticulos.setHeight(0);
recyclerArticulos.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getContext(), "No se ha podido establecer conexión con el servidor" +
" "+response, Toast.LENGTH_LONG).show();
}
}
};
}
private Response.ErrorListener createMyReqErrorListenerArticulos() {
return new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "No se ha podido conectar con el servidor" + error, Toast.LENGTH_LONG).show();
Log.i("ERROR", error.toString());
}
};
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Articulos_item.xml
------------------
<?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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/idArticulo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="18"
android:text="id"
android:textSize="16sp"
android:visibility="invisible" />
<TextView
android:id="@+id/tituloArticulo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="6"
android:text="titulo"
android:textSize="16sp" />
<TextView
android:id="@+id/fechaArticulo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="13"
android:text="fecha"
android:textSize="16sp" />
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:background="#979B9C"/>
</LinearLayout>
fragment_listado_articulos.xml
------------------------------
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/contenListadoArticulos"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFE2E7EA"
tools:context=".gestion_datos.ListadoArticulos">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@drawable/border_style2"
android:paddingBottom="6dp"
android:paddingTop="6dp"
android:text="Listado Artículos"
android:textAlignment="center"
android:textSize="16dp"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/IdReciclerViewListadoArticulos"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:textAlignment="center">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</ScrollView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tvLoadingListadoArticulos"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorNaranjaCrema2"
android:gravity="center"
android:text="cargando ...."
android:textSize="20dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:padding="2dp"
android:text="Selecciona un Un Artículo"
android:textSize="16dp" />
</LinearLayout>
</LinearLayout>
</FrameLayout>
fragment_comentarios_articulo.xml
----------------------------------
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/contenComentariosArticulo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/coloNaranjaCremar"
tools:context=".gestion_datos.ComentariosArticulo">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
</FrameLayout>
答案 0 :(得分:0)
这是因为您将CommentariosArticulo片段作为子项添加到ListadoArticulos片段中,并且CommentariosArticulo片段和recyclerview位于相同的FrameLayout contenListadoArticulos中。
您需要替换MainActivity类中的片段而不是ListadoArticulos中的片段。
只需将以下代码从ListadoArticulos移至MainActivity
即可Fragment miFragment = new ComentariosArticulo();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
//el id:R.id.BuscarArticulosCategoria pertenece al
//contenedor del fragment_buscar_articulos_categoria.xml (fragment actual)
transaction.replace(R.id.contenListadoArticulos, miFragment);
transaction.addToBackStack(null);
// Commit a la transacción
transaction.commit();