2012-01-09 51 views
0

我已經創建了一個自定義視圖組件,並且我的佈局文件由一個按鈕和CustomView組成。每當我按下按鈕時,我想要更新CustomView類中的文件名。通過調用的set_file方法customviewset_file方法在函數中調用perform();。但是我這樣做的時候出錯。如何通過從按鈕調用功能來調用「自定義視圖」中的設置更改?

這是我的3班。

TestActivity.java

包com.android.pack;

import java.net.URISyntaxException;

import android.app.Activity; 
import android.content.Context; 
import android.content.Intent; 
import android.net.Uri; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup.LayoutParams; 
import android.widget.Button; 
import android.widget.LinearLayout; 
import android.widget.Toast; 

    public class TestActivity extends Activity { 
    /** Called when the activity is first created. */ 
    int height; 
    int weight; 
    Button select; 
    customview cView; 
    String path=""; 
     String pathchk=""; 
     String temp=""; 

    private static final int FILE_SELECT_CODE = 0; 

     public void perform() 
     { 
      cView.set_file(pathchk); 
      cView.postInvalidate(); 
     } 
     public void showFileChooser(View v) { 
      Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
      intent.setType("*/*"); 
      intent.addCategory(Intent.CATEGORY_OPENABLE); 

      try { 
       startActivityForResult(
         Intent.createChooser(intent, "Select a File to Upload"), 
         FILE_SELECT_CODE); 

      } catch (android.content.ActivityNotFoundException ex) { 
       // Potentially direct the user to the Market with a Dialog 
       Toast.makeText(this, "Please install a File Manager.", 
         Toast.LENGTH_SHORT).show(); 
      } 
     } 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    { 
      switch (requestCode) { 
       case FILE_SELECT_CODE:  
       if (resultCode == RESULT_OK) { 
        // Get the Uri of the selected file 
        Uri uri = data.getData(); 
        Log.v("check", "File Uri: " + uri.toString()); 
        // Get the path 

        try { 
         path = FileUtils.getPath(this, uri); 
         pathchk=path.substring(12); 
         perform(); 



        } catch (URISyntaxException e) { 
         // TODO Auto-generated catch block 
         Log.v("error", "File Path: "+pathchk); 
        } 
        Log.v("check", "File Path: "+path); 
        // Get the file instance 
        // File file = new File(path); 
        // Initiate the upload 
       }   
       break; 
      } 
     super.onActivityResult(requestCode, resultCode, data); 
     } 
    @Override 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View v=li.inflate(R.layout.main, null); 
     cView = (customview)findViewById(R.id.customview1); 

     LinearLayout ll = new LinearLayout(this); 
     ll.setOrientation(LinearLayout.VERTICAL); 
     select=(Button)findViewById(R.id.button1); 
     // select.setText("Select a File"); 
     /* select.setOnClickListener(new Button.OnClickListener(){ 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       showFileChooser(); 
       Toast.makeText(getApplicationContext(), "The File "+path+" is loaded",Toast.LENGTH_LONG);   } 





       }); */ 


     // LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
      // LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); 




     //ll.addView(select, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 

     //ll.addView(cView, layoutParams); 

     setContentView(R.layout.main); 



    } 
} 

customview.java

package com.android.pack; 

import java.io.BufferedReader; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileReader; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.StringTokenizer; 

import android.app.AlertDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.gesture.Gesture; 
import android.gesture.GesturePoint; 
import android.gesture.GestureStroke; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.Paint; 
import android.graphics.Path; 
import android.graphics.Point; 
import android.os.Environment; 
import android.util.AttributeSet; 
import android.util.Log; 
import android.view.View; 
import android.view.View.* 
; 
import android.widget.Button; 
import android.widget.Toast; 

public class customview extends View implements OnClickListener 
{ 
    ArrayList<GesturePoint> child; 
    ArrayList<Point> pnts; 
    Point pnt=new Point(); 
    File myFile; 
    BufferedReader br; 
    FileInputStream in; 
    InputStreamReader fin; 
    GestureStroke gest; 
    Gesture my_final=new Gesture(); 
    String Token; 
    long Time=30000000; 
    int flag=0; 
    boolean line=true; 
    boolean points=true; 
    Button b1; 
    int height; 
    int weight; 
    String Filename=""; 

    ArrayList<Path> paths; 

    Path mypath; 
    Paint mypaint=new Paint();// 
    public void set_file(String a)// to set the File 
    { 
     Filename=a; 
     //clear_screen(); 
    } 
    public customview(Context context) 
    { 
     super(context); 
     this.setOnClickListener(this); 
     mypaint.setColor(Color.RED); 
     mypaint.setAntiAlias(true); 
     mypaint.setStyle(Paint.Style.STROKE); 
     mypaint.setStrokeWidth(5); 
     myFile=Environment.getExternalStorageDirectory(); 

    } 
    public customview(Context context,AttributeSet att) 
    { 
     super(context,att); 
     this.setOnClickListener(this); 
     mypaint.setColor(Color.RED); 
     mypaint.setAntiAlias(true); 
     mypaint.setStyle(Paint.Style.STROKE); 
     mypaint.setStrokeWidth(5); 
     myFile=Environment.getExternalStorageDirectory(); 
    } 
    public void make_shape() 
    { 
     paths=new ArrayList<Path>(); 
     pnts=new ArrayList<Point>(); 
     height=this.getHeight(); 
     weight=this.getWidth(); 
     Log.v("Main_custom_height",height+""); 
     Log.v("Main_custom_weight",weight+""); 
      try 
      { 
      File file = new File(myFile,Filename); 
      br=new BufferedReader(new FileReader(file)); 

      String read; 
      while((read=br.readLine())!=null) 
      { 

       //Toast.makeText(Create_pathActivity.this,read,Toast.LENGTH_SHORT).show(); 
       if(read.equals(".PEN_UP")) 
       { 
        flag=0; 
        gest=new GestureStroke(child); 
        mypath=gest.getPath(); 
        paths.add(mypath); 
        my_final.addStroke(gest); 

       } 
       if(flag==1) 
       { 
        StringTokenizer st = new StringTokenizer(read); 
         for(int i=0;i<=2;i++) 
         { 
          if(i==0) 
          { 
           Token=st.nextToken(); 
           pnt.x=Integer.parseInt(Token); 
           //pnt.x=pnt.x+200; 
           //pnt.x=pnt.x/5; 

           Log.v("PointX",Token); 
          } 
          if(i==1) 
          { 
           Token=st.nextToken(); 
           pnt.y=Integer.parseInt(Token); 
           //pnt.y=pnt.y+165; 
           //pnt.y=pnt.y/5; 
           Log.v("PointY",Token); 
          } 
          if(i==2) 
          { 

           Time=Time+10; 
           GesturePoint temp=new GesturePoint(pnt.x,pnt.y,Time); 
           child.add(temp); 
          } 

         } 
         Point p=new Point(); 
         p.x=pnt.x; 
         p.y=pnt.y; 
         pnts.add(p); 


       } 
       if(read.equals(".PEN_DOWN")) 
       { 
        flag=1; 
        child=new ArrayList<GesturePoint>(); 
       } 
      } 

     }catch (Exception e) 
     { 


     } 
    } 


    protected void onDraw(Canvas canvas) 
    { 
     if(points==true && line==false) 
     { 

       for (Point point : pnts) { 
        canvas.drawCircle(point.x, point.y, 3,mypaint); 
       } 

     } 
     if(points==false && line==true) 
     { 
          for(int i=0;i<paths.size();i++) 
       { 
        canvas.drawPath(paths.get(i), mypaint); 
       } 

     } 

    } 
    public void scale() 
    { 
     int S_width = 320, S_height = 410, width, height, DiffW, DiffH; 
      int max_x = 0, max_y = 0, min_x = 320, min_y = 410; 
      int new_x, new_y; 
      int i; 
      float scale; 


      for(i=0; i<pnts.size(); i++) 
      { 
      if(pnts.get(i).x > max_x) 
       max_x = pnts.get(i).x; 

      if(pnts.get(i).x < min_x) 
       min_x = pnts.get(i).x; 

      if(pnts.get(i).y > max_y) 
       max_y = pnts.get(i).y; 

      if(pnts.get(i).y < min_y) 
       min_y = pnts.get(i).y; 

      } 

      width = max_x - min_x; 
      height = max_y - min_y; 

      DiffW = Math.abs(S_width - width); 
      DiffH = Math.abs(S_height - height); 

      if(DiffW > DiffH) 
       scale = width/300; 
      else 
       scale = height/390; 

      //scaling 
      for(i=0; i<pnts.size(); i++) 
      { 
       pnts.get(i).x /= scale; 
       pnts.get(i).y /= scale; 
      } 

      new_x = max_x - 10; 
      new_y = min_y - 10; 

      //top-left shifting 
      for(i=0; i<pnts.size(); i++) 
      { 
       pnts.get(i).x -= new_x; 
       pnts.get(i).y -= new_y; 
      } 

    } 



    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 
     if(Filename.equals("")) 
     { 
      Toast.makeText(getContext(),"Select a file ist", Toast.LENGTH_SHORT); 
      return; 
     } 
     make_shape(); 

     AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); 
     builder.setCancelable(true); 
     builder.setTitle("Draw a line or a path"); 
     builder.setInverseBackgroundForced(true); 
     builder.setPositiveButton("Line", new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      line=true; 
      points=false; 
      invalidate(); 
       } 
     }); 
     builder.setNegativeButton("Point", new DialogInterface.OnClickListener() { 
      @Override 
     public void onClick(DialogInterface dialog, int which) { 
     line=false; 
     points=true; 
     //scale(); 
     invalidate(); 
      } 
     }); 
     AlertDialog alert = builder.create(); 
     alert.show(); 


    } 


} 

**FileUtils.java** 


package com.android.pack; 

import java.net.URISyntaxException; 

import android.content.Context; 
import android.database.Cursor; 
import android.net.Uri; 

public class FileUtils { 

    public static String getPath(Context context, Uri uri) throws URISyntaxException { 
     if ("content".equalsIgnoreCase(uri.getScheme())) { 
      String[] projection = { "_data" }; 
      Cursor cursor = null; 

      try { 
       cursor = context.getContentResolver().query(uri, projection, null, null, null); 
       int column_index = cursor 
       .getColumnIndexOrThrow("_data"); 
       if (cursor.moveToFirst()) { 
        return cursor.getString(column_index); 
       } 
      } catch (Exception e) { 
       // Eat it 
      } 
     } 

     else if ("file".equalsIgnoreCase(uri.getScheme())) { 
      return uri.getPath(); 
     } 

     return null; 
    } 
} 

,這裏是我的main.xml中文件

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <com.android.pack.customview 
     android:id="@+id/customview1" 
     android:layout_width="wrap_content" 
     android:layout_height="419dp" 
     android:layout_weight="0.63" 
     /> 


    <Button 
     android:id="@+id/button1" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="select a file" 
     android:onClick="showFileChooser"/> 

</LinearLayout> 

我的日誌貓

01-09 12:04:42.038: D/szipinf(4990): Initializing inflate state 
01-09 12:04:42.248: D/dalvikvm(4990): GC_CONCURRENT freed 281K, 50% free 2860K/5639K, external 0K/0K, paused 4ms+8ms 
01-09 12:04:48.668: V/check(4990): File Uri: content://org.openintents.cmfilemanager/mimetype//mnt/sdcard/points.txt 
01-09 12:04:48.698: D/AndroidRuntime(4990): Shutting down VM 
01-09 12:04:48.698: W/dalvikvm(4990): threadid=1: thread exiting with uncaught exception (group=0x40018560) 
01-09 12:04:48.698: E/AndroidRuntime(4990): FATAL EXCEPTION: main 
01-09 12:04:48.698: E/AndroidRuntime(4990): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=android.intent.action.VIEW dat=content://org.openintents.cmfilemanager/mimetype//mnt/sdcard/points.txt }} to activity {com.android.pack/com.android.pack.TestActivity}: java.lang.NullPointerException 
01-09 12:04:48.698: E/AndroidRuntime(4990):  at android.app.ActivityThread.deliverResults(ActivityThread.java:2653) 
01-09 12:04:48.698: E/AndroidRuntime(4990):  at android.app.ActivityThread.handleSendResult(ActivityThread.java:2695) 
01-09 12:04:48.698: E/AndroidRuntime(4990):  at android.app.ActivityThread.access$2000(ActivityThread.java:123) 
01-09 12:04:48.698: E/AndroidRuntime(4990):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:969) 
01-09 12:04:48.698: E/AndroidRuntime(4990):  at android.os.Handler.dispatchMessage(Handler.java:99) 
01-09 12:04:48.698: E/AndroidRuntime(4990):  at android.os.Looper.loop(Looper.java:130) 
01-09 12:04:48.698: E/AndroidRuntime(4990):  at android.app.ActivityThread.main(ActivityThread.java:3835) 
01-09 12:04:48.698: E/AndroidRuntime(4990):  at java.lang.reflect.Method.invokeNative(Native Method) 
01-09 12:04:48.698: E/AndroidRuntime(4990):  at java.lang.reflect.Method.invoke(Method.java:507) 
01-09 12:04:48.698: E/AndroidRuntime(4990):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847) 
01-09 12:04:48.698: E/AndroidRuntime(4990):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605) 
01-09 12:04:48.698: E/AndroidRuntime(4990):  at dalvik.system.NativeStart.main(Native Method) 
01-09 12:04:48.698: E/AndroidRuntime(4990): Caused by: java.lang.NullPointerException 
01-09 12:04:48.698: E/AndroidRuntime(4990):  at com.android.pack.TestActivity.perform(TestActivity.java:32) 
01-09 12:04:48.698: E/AndroidRuntime(4990):  at com.android.pack.TestActivity.onActivityResult(TestActivity.java:64) 
01-09 12:04:48.698: E/AndroidRuntime(4990):  at android.app.Activity.dispatchActivityResult(Activity.java:3908) 
01-09 12:04:48.698: E/AndroidRuntime(4990):  at android.app.ActivityThread.deliverResults(ActivityThread.java:2649) 
01-09 12:04:48.698: E/AndroidRuntime(4990):  ... 11 more 

感謝任何幫助!

+1

什麼是錯誤? PLZ分享你logcat – Arslan 2012-01-09 06:31:20

+0

你好!錯誤是它的說「應用程序測試(進程com.android.pack已意外停止。請重試 – 2012-01-09 06:35:38

+0

我選擇了文件points.txt/sdcard/ – 2012-01-09 06:44:07

回答

0

您還沒有完成SetcontentView來調用findviewby id。您必須致電

cView =(customview)v.findViewById(R.id.customview1);

1

儘量把

setContentView(R.layout.main) 

只是supr.onCreate之後,而不是在最後。

super.onCreate(savedInstanceState); 
setContentView(R.layout.main); 
+0

它工作!!!謝謝:)但問題在哪裏?我的意思是setContentView的位置是如何影響的? – 2012-01-09 06:51:53

-1
You are trying to add button and layouts before setting its Layout main 
change 

setContentView(R.layout.main) 
before 
    LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     View v=li.inflate(R.layout.main, null); 
     cView = (customview)findViewById(R.id.customview1); 

     LinearLayout ll = new LinearLayout(this); 
     ll.setOrientation(LinearLayout.VERTICAL); 
     select=(Button)findViewById(R.id.button1); 
相關問題