2015-11-09 45 views
-1

請幫助..Android Studio帶有單選按鈕值的列表視圖 - 如何檢查單選按鈕並獲取值?

我有單選按鈕值列表視圖,但我的問題是我不知道要檢查每一個單選按鈕,並獲得價值..

這是我checkoutlayout1.xml

<?xml version="1.0" encoding="utf-8"?> 
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" 
    android:fillViewport="false" 
    android:background="#fffff1f1"> 
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="match_parent" android:layout_height="match_parent" 
     android:background="#fffff1f1" 
     android:orientation="horizontal" 
     android:gravity="center_horizontal" 
     android:paddingBottom="20dp"> 

     <FrameLayout 
      android:id="@+id/framelayout" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:background="#fffddbd7" 
      android:padding="10dp" 
      android:layout_marginTop="10dp" 
      android:layout_marginBottom="10dp"> 

      <RelativeLayout 
       android:layout_width="match_parent" 
       android:layout_height="match_parent"> 

       <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="STEP 1 OF 3 - DELIVERY INFORMATION" 
        android:id="@+id/textStep" 
        android:layout_centerVertical="true" 
        android:layout_centerHorizontal="true" 
        android:gravity="center" 
        android:textSize="17dp" /> 

      </RelativeLayout> 

     </FrameLayout> 

     <FrameLayout 
      android:id="@+id/framelayout2" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:background="#ff949596" 
      android:layout_below="@+id/framelayout" 
      android:padding="10dp" 
      android:layout_marginLeft="20dp" 
      android:layout_marginRight="20dp" 
      android:layout_marginBottom="10dp"> 

      <RelativeLayout 
       android:layout_width="match_parent" 
       android:layout_height="match_parent"> 

       <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Please select the preferred shipping method to use on this order." 
        android:id="@+id/textShipping" 
        android:layout_centerVertical="true" 
        android:layout_centerHorizontal="true" 
        android:gravity="center" 
        android:textColor="#ffffffff" /> 

      </RelativeLayout> 

     </FrameLayout> 

     <FrameLayout 
      android:id="@+id/framelayout3" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_below="@+id/framelayout2" 
      android:layout_marginLeft="20dp" 
      android:layout_marginRight="20dp" 
      android:padding="10dp"> 

      <RelativeLayout 
       android:layout_width="match_parent" 
       android:layout_height="match_parent"> 

       <com.example.administrator.mosbeau.ExpandableHeightListView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:id="@+id/shippinglist" 
        android:divider="@android:color/transparent" 
        android:dividerHeight="10dp" 
        android:background="#fffff1f1" 
        android:layout_below="@+id/textnote" 
        android:layout_marginBottom="20dp" 
        android:layout_marginTop="5dp"/> 

      </RelativeLayout> 

     </FrameLayout> 

     <FrameLayout 
      android:id="@+id/framelayout3" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:layout_below="@+id/framelayout4" 
      android:paddingLeft="50dp" 
      android:paddingRight="50dp" 
      android:layout_margin="20dp"> 

      <Button 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:text="CONTINUE" 
       android:id="@+id/btnContinue" 
       android:textColor="#ffffffff" 
       android:background="@drawable/cfa245_button" 
       android:textStyle="bold" /> 

     </FrameLayout> 


    </RelativeLayout> 
</ScrollView> 
在我的佈局

我有這樣的ListView

<com.example.administrator.mosbeau.ExpandableHeightListView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:id="@+id/shippinglist" 
    android:divider="@android:color/transparent" 
    android:dividerHeight="10dp" 
    android:background="#fffff1f1" 
    android:layout_below="@+id/textnote" 
    android:layout_marginBottom="20dp" 
    android:layout_marginTop="5dp"/> 

,這是我的shippingrate_item.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:background="#fffff1f1" 
    android:layout_height="fill_parent"> 

    <FrameLayout 
     android:id="@+id/framelayout" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:background="#fffff1f1"> 

     <RelativeLayout 
      android:layout_width="match_parent" 
      android:layout_height="match_parent"> 

      <TextView 
       android:id="@+id/textconfigurationid" 
       android:layout_width="wrap_content" 
       android:text="configuration_id" 
       android:layout_height="wrap_content" 
       android:visibility="invisible"/> 

      <RadioButton 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="shipping_title" 
       android:textColor="#666666" 
       android:id="@+id/radioShippingtitle" /> 

      <ImageView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/shipping_icon" 
       android:adjustViewBounds="true" 
       android:layout_toRightOf="@+id/radioShippingtitle" 
       android:layout_toEndOf="@+id/radioShippingtitle" 
       android:layout_marginLeft="10dp" 
       android:layout_marginTop="5dp" 
       android:maxHeight="20dp" 
       android:maxWidth="60dp" /> 

      <TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/textPrice" 
       android:text="shipping_price" 
       android:layout_toRightOf="@+id/shipping_icon" 
       android:layout_toEndOf="@+id/shipping_icon" 
       android:layout_marginLeft="10dp" 
       android:minHeight="32dp" 
       android:gravity="center_vertical" /> 

      <TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/textDesc" 
       android:text="shipping_desc" 
       android:layout_marginLeft="32dp" 
       android:layout_below="@+id/radioShippingtitle"/> 

     </RelativeLayout> 

    </FrameLayout> 

</RelativeLayout> 
在我的項目

我有這個無線電

<RadioButton 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="shipping_title" 
    android:textColor="#666666" 
    android:id="@+id/radioShippingtitle" /> 

我傳遞值到我的列表視圖項與我checkoutFragment1.java

package com.example.administrator.mosbeau; 

import android.app.AlertDialog; 
import android.app.Fragment; 
import android.app.FragmentManager; 
import android.app.ProgressDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.provider.Settings; 
import android.support.annotation.Nullable; 
import android.support.v7.app.ActionBar; 
import android.support.v7.app.ActionBarActivity; 
import android.util.Log; 
import android.view.Gravity; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.Button; 
import android.widget.FrameLayout; 
import android.widget.TextView; 
import android.widget.Toast; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.params.BasicHttpParams; 
import org.apache.http.params.HttpConnectionParams; 
import org.apache.http.params.HttpParams; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.text.DecimalFormat; 
import java.util.ArrayList; 
import java.util.HashMap; 

/** 
* Created by Administrator on 11/7/2015. 
*/ 
public class CheckoutFragment1 extends Fragment { 

    public static CheckoutFragment1 newInstance(String customersid, String countryid, String weightotal, String subtotal, String stateid) { 
     CheckoutFragment1 fragment = new CheckoutFragment1(); 

     Bundle bundle = new Bundle(); 
     bundle.putString("customersid", customersid); 
     bundle.putString("countryid", countryid); 
     bundle.putString("weightotal", weightotal); 
     bundle.putString("subtotal", subtotal); 
     bundle.putString("stateid", stateid); 
     fragment.setArguments(bundle); 

     return fragment; 
    } 

    public CheckoutFragment1() { 
    } 

    String customersid, countryid, weightotal, subtotal, stateid; 

    public static final int CONNECTION_TIMEOUT = 1000 * 15; 
    public static final String SERVER_ADDRESS = "http://shop.mosbeau.com.ph/android/"; 

    String myJSONShippingRate; 
    JSONArray jsonarrayShippingRate; 

    ExpandableHeightListView shippingratelistview; 
    ListViewAdapterShipping shippingrateadapter; 

    ProgressDialog mProgressDialog; 
    ArrayList<HashMap<String, String>> shippingratearraylist; 
    public static String configuration_id = "configuration_id"; 
    public static String shipping_title = "shipping_title"; 
    public static String shipping_icon = "shipping_icon"; 
    public static String shipping_price = "shipping_price"; 
    public static String shipping_desc = "shipping_desc"; 

    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ 
     View rootView = inflater.inflate(R.layout.checkoutlayout1, container, false); 

     ConnectivityManager cm = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); 
     boolean isConnected = activeNetwork != null && 
       activeNetwork.isConnectedOrConnecting(); 
     //boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI; 
     if(isConnected){ 
      getShippingRate(); 
     }else{ 
      nointernet(); 
     } 

     if(getArguments() != null) { 
      String ccustomersid = getArguments().getString("customersid"); 
      String ccountryid = getArguments().getString("countryid"); 
      String cweightotal = getArguments().getString("weightotal"); 
      String csubtotal = getArguments().getString("subtotal"); 
      String cstateid = getArguments().getString("stateid"); 

      customersid = ccustomersid; 
      countryid = ccountryid; 
      weightotal = cweightotal; 
      subtotal = csubtotal; 
      stateid = cstateid; 
     } 

     shippingratelistview = new ExpandableHeightListView(getActivity()); 
     shippingratelistview = (ExpandableHeightListView) rootView.findViewById(R.id.shippinglist); 

     //Toast.makeText(getActivity(),"custoid: "+customersid+" countryid: "+countryid+" weight: "+weightotal+"subtotal: "+subtotal+" stateid: "+stateid,Toast.LENGTH_SHORT).show(); 

     showGlobalContextActionBar(); 

     return rootView; 
    } 

    private void showGlobalContextActionBar() { 
     ActionBar actionBar = getActionBar(); 
     actionBar.setDisplayShowTitleEnabled(true); 
     actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); 
     actionBar.setTitle("CHECKOUT"); 
    } 

    private ActionBar getActionBar() { 
     return ((ActionBarActivity) getActivity()).getSupportActionBar(); 
    } 

    public void getShippingRate(){ 
     class DownloadJSONShippingRate extends AsyncTask<String, Void, String> { 

      @Override 
      protected void onPreExecute() { 
       super.onPreExecute(); 
       // Create a progressdialog 
       /*mProgressDialog = new ProgressDialog(getActivity()); 
       // Set progressdialog title 
       //mProgressDialog.setTitle(cname); 
       // Set progressdialog message 
       mProgressDialog.setMessage("Please wait..."); 
       mProgressDialog.setIndeterminate(false); 
       // Show progressdialog 
       mProgressDialog.show();*/ 
       mProgressDialog = ProgressDialog.show(getActivity(), null, null, true, false); 
       mProgressDialog.setContentView(R.layout.progressdialog); 
      } 

      @Override 
      protected String doInBackground(String... params) { 
       ArrayList<NameValuePair> dataToSend = new ArrayList<>(); 
       dataToSend.add(new BasicNameValuePair("customersid", customersid)); 
       dataToSend.add(new BasicNameValuePair("countryid", countryid)); 
       dataToSend.add(new BasicNameValuePair("stateid", stateid)); 
       dataToSend.add(new BasicNameValuePair("weightotal", weightotal)); 
       dataToSend.add(new BasicNameValuePair("subtotal", subtotal)); 

       HttpParams httpRequestParams = new BasicHttpParams(); 
       HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT); 
       HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT); 

       DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); 
       HttpPost httppost = new HttpPost(SERVER_ADDRESS + "shippingrate.php"); 

       // Depends on your web service 
       //httppost.setHeader("Content-type", "application/json"); 

       InputStream inputStream = null; 
       String shippingrateresult = null; 
       try { 
        httppost.setEntity(new UrlEncodedFormEntity(dataToSend)); 
        HttpResponse response = httpclient.execute(httppost); 
        HttpEntity entity = response.getEntity(); 

        inputStream = entity.getContent(); 
        // json is UTF-8 by default 
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); 
        StringBuilder sb = new StringBuilder(); 

        String line = null; 
        while ((line = reader.readLine()) != null) 
        { 
         sb.append(line + "\n"); 
        } 
        shippingrateresult = sb.toString(); 
       } catch (Exception e) { 
        // Oops 
       } 
       finally { 
        try{if(inputStream != null)inputStream.close();}catch(Exception squish){} 
       } 
       return shippingrateresult; 
      } 

      @Override 
      protected void onPostExecute(String shippingrateresult){ 
       myJSONShippingRate=shippingrateresult; 

       try { 
        // Locate the array name in JSON 
        JSONObject jsonObjcart = new JSONObject(myJSONShippingRate); 
        jsonarrayShippingRate = jsonObjcart.getJSONArray("shippingrate"); 
        shippingratearraylist = new ArrayList<HashMap<String, String>>(); 
        int qtySum = 0, qtyNum, tqtySum; 
        for (int i = 0; i < jsonarrayShippingRate.length(); i++) { 
         HashMap<String, String> lmap = new HashMap<String, String>(); 
         JSONObject p = jsonarrayShippingRate.getJSONObject(i); 
         // Retrive JSON Objects 
         lmap.put("configuration_id", p.getString("configuration_id")); 
         lmap.put("shipping_title", p.getString("shipping_title")); 
         lmap.put("shipping_desc", p.getString("shipping_desc")); 
         lmap.put("shipping_icon", p.getString("shipping_icon")); 
         lmap.put("shipping_price", p.getString("shipping_price")); 

         shippingratearraylist.add(lmap); 
        } 
       } catch (JSONException e) { 
        Log.e("Error", e.getMessage()); 
        e.printStackTrace(); 
       } 

       shippingrateadapter = new ListViewAdapterShipping(getActivity(), shippingratearraylist); 
       shippingratelistview.setAdapter(shippingrateadapter); 
       shippingratelistview.setExpanded(true); 

       // Close the progressdialog 
       mProgressDialog.dismiss(); 
      } 
     } 
     DownloadJSONShippingRate g = new DownloadJSONShippingRate(); 
     g.execute(); 
    } 

    public void nointernet(){ 
     AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity()); 
     dialogBuilder.setMessage("There seems to be a problem with your connection."); 
     dialogBuilder.setNegativeButton("Edit Settings", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       //Stop the activity 
       startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); 
      } 

     }); 
     dialogBuilder.setPositiveButton("Reload", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       //Stop the activity 
       HomeFragment homefragment = HomeFragment.newInstance(); 
       FragmentManager fragmentManager = getFragmentManager(); 
       fragmentManager.beginTransaction() 
         .replace(R.id.container, homefragment) 
         .addToBackStack(null) 
         .commit(); 
      } 

     }); 
     AlertDialog dialog = dialogBuilder.show(); 
     TextView messageText = (TextView)dialog.findViewById(android.R.id.message); 
     messageText.setGravity(Gravity.CENTER); 
     dialog.setCanceledOnTouchOutside(false); 
     dialog.setCancelable(false); 
     dialog.show(); 
    } 
} 

和我listviewadaptershipping.java

package com.example.administrator.mosbeau; 

import android.app.Activity; 
import android.app.AlertDialog; 
import android.app.FragmentManager; 
import android.app.ProgressDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.os.AsyncTask; 
import android.view.Gravity; 
import android.view.KeyEvent; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.view.inputmethod.EditorInfo; 
import android.widget.BaseAdapter; 
import android.widget.EditText; 
import android.widget.ImageButton; 
import android.widget.ImageView; 
import android.widget.RadioButton; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.bumptech.glide.Glide; 
import com.bumptech.glide.load.engine.DiskCacheStrategy; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.params.BasicHttpParams; 
import org.apache.http.params.HttpConnectionParams; 
import org.apache.http.params.HttpParams; 
import org.json.JSONArray; 

import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.StringTokenizer; 

/** 
* Created by Administrator on 11/9/2015. 
*/ 
public class ListViewAdapterShipping extends BaseAdapter { 

    boolean expanded = false; 

    // Declare Variables 
    Context context; 
    LayoutInflater inflater; 
    ArrayList<HashMap<String, String>> data; 
    HashMap<String, String> resultp = new HashMap<String, String>(); 

    public ListViewAdapterShipping(Context context, 
          ArrayList<HashMap<String, String>> arraylist) { 
     this.context = context; 
     data = arraylist; 
    } 

    @Override 
    public int getCount() { 
     return data.size(); 
    } 

    @Override 
    public Object getItem(int position) { 
     return null; 
    } 

    @Override 
    public long getItemId(int position) { 
     return 0; 
    } 

    public View getView(final int position, View convertView, ViewGroup parent) { 
     // Declare Variables 
     TextView configuration_id; 
     RadioButton shipping_title; 
     ImageView shipping_icon; 
     TextView shipping_price; 
     TextView shipping_desc; 

     inflater = (LayoutInflater) context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     View itemView = inflater.inflate(R.layout.shippingrate_item, parent, false); 
     // Get the position 
     resultp = data.get(position); 

     // Locate the TextViews in product_gridview_item.xml 
     configuration_id = (TextView) itemView.findViewById(R.id.textconfigurationid); 
     shipping_title = (RadioButton) itemView.findViewById(R.id.radioShippingtitle); 
     shipping_icon = (ImageView) itemView.findViewById(R.id.shipping_icon); 
     shipping_price = (TextView) itemView.findViewById(R.id.textPrice); 
     shipping_desc = (TextView) itemView.findViewById(R.id.textDesc); 

     // Capture position and set results to the TextViews 
     configuration_id.setText(resultp.get(CheckoutFragment1.configuration_id)); 
     shipping_title.setText(resultp.get(CheckoutFragment1.shipping_title)); 
     shipping_price.setText(resultp.get(CheckoutFragment1.shipping_price)); 
     shipping_desc.setText(resultp.get(CheckoutFragment1.shipping_desc)); 
     // Capture position and set results to the ImageView 
     Glide.with(context).load(resultp.get(CheckoutFragment1.shipping_icon)).diskCacheStrategy(DiskCacheStrategy.ALL).into(shipping_icon); 
     int color = 0xffffffff; 
     itemView.setBackgroundColor(color); 

     return itemView; 
    } 
} 

現在的問題是我想單擊單選按鈕,並獲得textconfigurationid,並通過可變

請幫助我..

感謝

回答

0

嘗試使用radioButton.isChecked (),它會告訴你單選按鈕是否被選中。此外,您還可以使用

radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 

     } 

    }); 
0

我解決我的問題與此代碼..

mconfiguration_id = configuration_id.getText().toString(); 
     shipping_title.setTag(mconfiguration_id); 
     shipping_title.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       if (position != mSelectedPosition && mSelectedRB != null) { 
        mSelectedRB.setChecked(false); 
       } 

       mSelectedPosition = position; 
       mSelectedRB = (RadioButton) v; 

       String mconfiguration_id; 
       mconfiguration_id = v.getTag().toString(); 
       Toast.makeText(context, mconfiguration_id, Toast.LENGTH_SHORT).show(); 
      } 

     }); 

     if(mSelectedPosition != position){ 
      shipping_title.setChecked(false); 
     }else{ 
      shipping_title.setChecked(true); 
      if(mSelectedRB != null && shipping_title != mSelectedRB){ 
       mSelectedRB = shipping_title; 
      } 
     } 
1

我不能正確理解你的問題,但你想要得到單選按鈕和TextView的(textconfigurationid的價值是什麼我猜)存儲在一個變量中。

您可以在BaseAdapter的getView方法中處理您的點擊事件。 類似這樣的:

public View getView(final int position, View convertView, ViewGroup parent) { 
    //*** 
       Your code here.. 
           ***//  
    itemView.setBackgroundColor(color); 

    //You can get value of radio button and textview like this. 
    Boolean radioValue = shipping_title.isChecked(); 
    int configId = configuration_id.getText(); 

    return itemView; 
} 
相關問題